﻿from PySide6.QtCore import QDateTime, Slot
from PySide6.QtWidgets import QMessageBox
from PySide6.QtGui import QIcon
from Devices.DeviceWindow import DeviceWindow
from Devices.Chiot.MatterPlug.DeviceMatterPlug import DeviceMatterPlug
from Devices.Chiot.MatterPlug.MatterPlugParser import MatterPlugParser

from Devices.Chiot.MatterPlug.Forms.MatterPlugWindow_UI import Ui_FormMatterPlugWindow

class MatterPlugWindow(DeviceWindow):
    def __init__(self, supportDevice, parent = None):
        super().__init__(supportDevice, parent)

        self.__ui = Ui_FormMatterPlugWindow()
        self.__ui.setupUi(self)
        self.SetupUi(self.__ui)
        
        self.__DeviceFullStatus = DeviceMatterPlug.DeviceFullStatus()

        self._HttpServerWindow.SetLogServerEnable(False)
        self._OtaUrl = self.__ui.lineEdit_downloadUrl.text()

        self.__ui.tabWidget.setCurrentIndex(0)
        self.__ui.progressBar_Ota.setVisible(False)

    def Connect(self, cmdPort, logPort):
        super().Connect(cmdPort, logPort)
        self.__ui.lineEdit_downloadUrl.setText(self._OtaUrl % (self._HttpServerWindow.GetIP(), self._HttpServerWindow.GetPort(), self._SupportDevice.deviceBinName))

    def Connected(self, ip, port):
        cmd = MatterPlugParser.PackGetFullStatus()
        self.SendCommandText(cmd)

    def SetDeviceFullStatus(self, msgValue):
        if MatterPlugParser.ParseFullStatus(msgValue, self.__DeviceFullStatus):
            #基本信息
            self.__ui.label_Mac.setText(self.__DeviceFullStatus.mac)
            self.__ui.label_firmwareVersion.setText(self.__DeviceFullStatus.firmwareVersion)
            self.__ui.label_hardwareVersion.setText(self.__DeviceFullStatus.hardwareVersion)
            self.__ui.label_protocol.setText(self.__DeviceFullStatus.protocol)

            self.__ui.label_buildTime.setText(self.__DeviceFullStatus.buildTime)

    def CmdDateReceived(self, data):
        ret, msgName, msgValue = MatterPlugParser.ParseMsg(data)
        if not ret:
            return

        if msgName == "getFullStatus":
            self.SetDeviceFullStatus(msgValue)
            self.ShowMessageBox("设备信息同步", "信息同步成功!")
        elif msgName == "heartbeat":
            self.SetDeviceFullStatus(msgValue)
            self.ShowMessageBox("设备信息同步", "信息同步成功!")
        elif msgName == "rptStatus":
            self.SetDeviceFullStatus(msgValue)
        elif msgName == "otaProcess":
            if self._OtaStarted:
                otaProcess = DeviceMatterPlug.OtaProcess()
                MatterPlugParser.ParseOtaProcess(msgValue, otaProcess)
                if len(otaProcess.startTime) > 0 and len(otaProcess.totalTime) > 0:
                    startTime = otaProcess.startTime.toLongLong()
                    startDateTime = QDateTime.fromMSecsSinceEpoch(startTime).toString("yyyy-MM-dd HH:mm:ss")
                    self._OtaStarted = False
                    self.ShowMessageBox("设备升级", "设备升级开始\r\n开始时间\"%s\",预计用时%2秒!" % (startDateTime, otaProcess.totalTime))
                else:
                    if otaProcess.progress.isdigit():
                        progress = int(otaProcess.progress)
                        self.__ui.progressBar_Ota.setVisible(100 != progress)
                        self.__ui.progressBar_Ota.setValue(progress)

                    if otaProcess.process.isdigit():
                        process = int(otaProcess.process)
                        if 1 == process:
                            self._OtaStarted = False
                            self.ShowMessageBox("设备升级", "设备下载完成,等待安装...")
        
    @Slot()
    def on_pushButton_Sync_clicked(self):
        cmd = MatterPlugParser.PackGetFullStatus()
        self.SendCommandText(cmd)
                                    
    @Slot()
    def on_pushButton_unbind_clicked(self):
        cmd = MatterPlugParser.PackUnbind()
        self.SendCommandText(cmd)
                      
    @Slot()
    def on_pushButton_upgrade_clicked(self):
        cmd = MatterPlugParser.PackUpgrade(self.__ui.lineEdit_upgradePackageId.text(), self.__ui.lineEdit_downloadUrl.text(), self.__ui.label_Mac.text(), self.__ui.lineEdit_newVersion.text(), self.__ui.lineEdit_md5.text(), self.__ui.lineEdit_size.text())
        self.SendCommandText(cmd)
        self._OtaStarted = True
                                    
    def HttpStarted(self):
        self.__ui.lineEdit_downloadUrl.setText(self._OtaUrl % (self._HttpServerWindow.GetIP(), self._HttpServerWindow.GetPort(), self._SupportDevice.deviceBinName))

    def HttpStopped(self):
        pass

